/**
 * 主题管理工具
 */

export type Theme = "light" | "dark" | "auto";

// 保存 MediaQuery 监听器引用，用于清理
let themeMediaQuery: MediaQueryList | null = null;
let themeChangeHandler: ((e: MediaQueryListEvent) => void) | null = null;

/**
 * 设置主题
 */
export function setTheme(theme: Theme) {
  if (!isValidTheme(theme)) {
    throw new Error('"theme" must be one of "light", "dark" or "auto".');
  }

  if (theme !== "auto") {
    // 如果不是 auto 模式，清理旧的监听器
    if (themeMediaQuery && themeChangeHandler) {
      themeMediaQuery.removeEventListener("change", themeChangeHandler);
      themeMediaQuery = null;
      themeChangeHandler = null;
    }
    document.querySelector("html")?.setAttribute("data-theme", theme);
    return;
  }

  // 自动主题模式
  // 先移除旧的监听器（如果存在）
  if (themeMediaQuery && themeChangeHandler) {
    themeMediaQuery.removeEventListener("change", themeChangeHandler);
  }

  const darkScheme = "(prefers-color-scheme: dark)";
  const prefersDarkScheme = window.matchMedia(darkScheme).matches;
  setTheme(prefersDarkScheme ? "dark" : "light");

  // 添加新监听器并保存引用
  themeMediaQuery = window.matchMedia(darkScheme);
  themeChangeHandler = (e) => {
    setTheme(e.matches ? "dark" : "light");
  };
  themeMediaQuery.addEventListener("change", themeChangeHandler);
}

/**
 * 验证主题是否有效
 */
function isValidTheme(theme: string): theme is Theme {
  return ["light", "dark", "auto"].includes(theme);
}

/**
 * 获取当前主题
 */
export function getCurrentTheme(): Theme {
  const html = document.querySelector("html");
  const theme = html?.getAttribute("data-theme");
  return (theme as Theme) || "light";
}

/**
 * 切换主题
 */
export function toggleTheme(): Theme {
  const currentTheme = getCurrentTheme();
  const newTheme = currentTheme === "light" ? "dark" : "light";
  setTheme(newTheme);
  return newTheme;
}
